// pages/Tabbar/ShoppingCart/ShoppingCart.js
//获取应用实例
const app = getApp()
import { getShoppingCartGoods , updateShoppingCartGoods , queryGoodsCommonConfig , queryGoodsListTab } from '../../../api/goods';
import { queryGoodsPurchaseRecord } from '../../../api/order';
const regeneratorRuntime = require('../../../common/runtime');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    shoppingCard: [], // 购物车商品列表
    isAllSel: false, // 是否全选
    allAmount: 0, // 总商品价格
    type: 0,
    areaList: [], // 分区列表
    timeList: [{//时间数组
      title: "a倒计时",
      endTime: "2020-08-23 18:00:00",
      }, {
      title: "b倒计时",
      endTime: "2020-08-25 20:00:00",
      }, {
      title: "c倒计时",
      endTime: "2020-08-21 20:00:00",
      }
    ],
    recordTotal: 0, // 疯抢人数
    recordList: [], // 疯抢人员列表
    goodsList: [], // 商品列表
    storehouseId: wx.getStorageSync('storehouseId'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._queryGoodsArea();
    this._queryGoodsPurchaseRecord();
    this._getGoods();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getGoods();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getGoods();
    this._queryGoodsArea();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取购物车商品信息
  getGoods(){
    let _this = this;
    getShoppingCartGoods()
    .then(async res => {
      if(res.success){
        if(res.data['result'].length > 0){
          var sum = 0;
          var timeList = [];
          var updateStockList = [];
          for (let index = 0; index < res.data['result'].length; index++) {
            const cart = res.data['result'][index];
            if(cart.isSelect == '1') sum++;
            if(cart.isFlashSale == '1'){
              var obj = {
                id: cart.id,
                endTime: cart.flashSaleEndTime,
              }
              timeList.push(obj)
            }
            if(cart.stock < cart.quantity){
              updateStockList.push(cart);
              await _this._updateCardGoods({id: cart.id,quantity: cart.stock,isSelect: cart.isSelect,});
            }
          }
          if(updateStockList.length > 0){
            _this.getGoods();
          }else{
            _this.setData({
              isAllSel: (sum == res.data['result'].length ? true : false),
              timeList: timeList,
            })
            _this.severalCountDown();
          }
          // res.data['result'].forEach(async (cart) =>{
          //   // if(cart.status == 0 || cart.status == 2){
          //   //   cart.isSelect = '0'
          //   // }
            
          // });
          
        }
        _this.setData({
          shoppingCard : res.data.result,
          allAmount : res.data.totalSellingPrice * 100,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 单个商品取消选择
  async selChange(e){
    console.log(e);
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let _this = this;
    try {
      await _this._updateCardGoods({id: item.id,isSelect: item.isSelect == '1' ? '0' : '1',quantity: item.quantity,goodsDetailsId: item.goodsDetailsId});
      _this.getGoods();
    } catch (error) {
      wx.showToast({
        title: error,
        icon: 'none'
      })
    }
  },
  // 全部商品取消或全选
  async allSelChange(){
    let _this = this;
    var array = _this.data.shoppingCard;
    try {
      for (let index = 0; index < array.length; index++) {
        const item = array[index];
        await _this._updateCardGoods({id: item.id,isSelect: _this.data.isAllSel == '1' ? '0' : '1',quantity: item.quantity > item.stock ? item.stock : item.quantity,goodsDetailsId: item.goodsDetailsId});
      }
      _this.getGoods();
    } catch (error) {
      wx.showToast({
        title: error,
        icon: 'none'
      })
    }
  },
  quantityTap(){},
  // 修改商品数量
  async quantityChange(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(e,'e')
    let _this = this;
    try {
      await _this._updateCardGoods({id: item.id,quantity: e.detail,isSelect: item.isSelect,goodsDetailsId: item.goodsDetailsId});
      _this.getGoods();
    } catch (error) {
      wx.showToast({
        title: error,
        icon: 'none'
      })
    }
  },
  // 修改购物车商品信息
  _updateCardGoods({id,quantity,goodsDetailsId,isSelect,isDelete}){
    return new Promise((resolve,reject) => {
      updateShoppingCartGoods({id: id,quantity: quantity,isSelect: isSelect,isDelete: isDelete})
      .then(res => {
        if(res.success){
          resolve();
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // 修改结算方式
  typeChange(){
    let _this = this;
    _this.setData({
      type: _this.data.type == '0' ? '1' : '0'
    })
  },
  // 结算按钮
  onClickButton(){
    let _this = this;
    var arr = [];
    var array = _this.data.shoppingCard;
    for (let index = 0; index < array.length; index++) {
      const item = array[index];
      if(item.isSelect == '1'){
        arr.push(item);
      }
    }
    if(arr.length > 0){
      if(this.data.type == '0'){
        var hasOverSeckill = false;
        for (let index = 0; index < arr.length; index++) {
          const item = arr[index];
          if(item.isFlashSale == '1'){
            if(new Date(item.flashSaleEndTime.replace(/-/g, "/")).getTime() - new Date().getTime() < 0){
              hasOverSeckill = true;
            }
          }
        }
        if(hasOverSeckill){
          wx.showToast({
            title: '当前含有秒杀结束的商品，请取消选择后再进行操作',
            icon: 'none',
          })
          return;
        }
        this.buy(arr);
      }else{
        this.del(arr);
      }
    }else{
      wx.showToast({
        title: '请选择需要结算的商品',
        icon: 'none',
      })
    }
  },
  // 去结算
  buy(arr){
    wx.navigateTo({
      url: `/pages/Orders/SubmitOrder/SubmitOrder?item=${JSON.stringify(arr)}`,
    })
  },
  // 删除
  del(arr){
    let _this = this;
    wx.showModal({
      title: '温馨提示',
      content: '确认删除选中商品？',
      success: async(res) => {
        if (res.confirm) {
          try {
            for (let index = 0; index < arr.length; index++) {
              const item = arr[index];
              await _this._updateCardGoods({id: item.id,isDelete: '1'});
            }
            _this.getGoods();
          } catch (error) {
            wx.showToast({
              title: error,
            })
          }
        }
      }
    })
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        if(item.status == '2'){
          wx.setStorageSync('shoppingCartId', item.id)
        }else{
          wx.setStorageSync('shoppingCartId', '')
        }
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 获取商品分区情况
  _queryGoodsArea(){
    let _this = this;
    queryGoodsCommonConfig({type: '1'})
    .then(async res => {
      if(res.success){
        _this.setData({
          areaList: res.data.content,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  //时间显示小于10的前面补0方法
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //多个倒计时函数
  severalCountDown: function () {
    var that = this;
    var time = 0;
    var obj = {};
    var timeList = that.data.timeList;
    //遍历数组，计算每个item的倒计时秒数
    timeList.forEach(function (item) {
      var endTime = new Date(item.endTime.replace(/-/g, "/")).getTime();//结束时间时间戳
      var currentTime = new Date().getTime();//当前时间时间戳
      time = (endTime - currentTime) / 1000;
      // 如果活动未结束
      if (time > 0) {
        var hou = parseInt(time / (60 * 60));
        var min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        var sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          hou: that.timeFormat(hou),
          min: that.timeFormat(min),
          sec: that.timeFormat(sec)
        }
      } else { //活动已结束
        obj = {
          hou: "00",
          min: "00",
          sec: "00"
        }
        clearTimeout(that.data.timeIntervalSeveral); //清除定时器
      }
      item.time = obj;
    })
    var timeIntervalSeveral = setTimeout(that.severalCountDown, 1000);
    that.setData({
      timeIntervalSeveral,
      timeList,
    })
  },
  // 获取商品列表信息
  _getGoods(){
    let _this = this;
    var storehouseId = wx.getStorageSync('storehouseId');
    queryGoodsListTab({size: 20,storehouseId: storehouseId,areaId: '0'})
    .then(res => {
      if(res.success){
        _this.setData({
          goodsList: res.data.content,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查询商品购买记录（包含假数据）
  _queryGoodsPurchaseRecord(){
    let _this = this;
    queryGoodsPurchaseRecord({storehouseId: _this.data.storehouseId})
    .then(res => {
      if(res.success){
        _this.setData({
          recordList: res.data.content,
          recordTotal: res.data.totalElements,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 删除单个购物车商品
  async delShoppingCart(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    await this._updateCardGoods({id: item.id,isDelete: '1'});
    wx.showToast({
      title: '删除成功',
      icon: 'none',
    })
    this.getGoods();
  },
})